package com.kakame.codenews.base.web.websocket.handler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import com.kakame.codenews.base.constant.SystemConstant;
import com.kakame.codenews.front.message.service.FrontMessageService;

/**
 * <pre>
 * <b>desc:</b> 建立连接，发送消息，关闭连接自动执行 
 * <b>auth:</b> ex-hejm
 * <b>date:</b> 2018年8月9日 下午2:46:37
 * </pre>
 */
public class SiteInnerMessageHandler extends TextWebSocketHandler{
 
    private Logger logger = LoggerFactory.getLogger(this.getClass().getPackage().getName());
    
	// 在线用户列表
    private static final List<WebSocketSession> users = new ArrayList<>();
	
    @Resource
    private FrontMessageService messageService;
    
	/**
	 * 成功建立连接触发的方法，
	 */
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
	    users.add(session);
        String userId = (String) session.getAttributes().get(SystemConstant.WEBSOCKET_USERID);
        if(userId != null){
            //查询未读消息
            int count = messageService.countNoReadMessage(userId);

            session.sendMessage(new TextMessage(count + ""));
        }
    }
	
	@Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) {
    }
	
	 /**
     * 发送信息给指定用户
     * @param userId
     * @param message
     * @return
     */
    public void sendMessageToUser(String userId, TextMessage message) {
        for (WebSocketSession user : users) {
            if (user.getAttributes().get(SystemConstant.WEBSOCKET_USERID).equals(userId)) {
                try {
                    if (user.isOpen()) {
                        user.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }
    
    /**
     * 广播信息（给所有在线用户发送消息）
     * @param message
     * @return
     */
    public void sendMessageToAllUsers() {
        for (WebSocketSession user : users) {
            try {
                if (user.isOpen()) {
                    //查询未读消息
                    int count = messageService.countNoReadMessage((String)user.getAttributes().get(SystemConstant.WEBSOCKET_USERID));
                    user.sendMessage(new TextMessage(count + ""));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    
    
    /**
     * 当链接发生异常后触发的方法，关闭出错会话的连接，和删除在Map集合中的记录
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
    		//判断当前的链接是否在继续，关闭连接
    	if (session.isOpen()) {
            session.close();
        }
    	logger.debug("websocket connection closed......");
        users.remove(session);
    }
    
    /**
     * 当链接关闭后触发的方法，连接已关闭，移除在Map集合中的记录。
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        logger.debug("websocket connection closed......");
        users.remove(session);
    }
    
    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
    
    
    
}